﻿using Microsoft.EntityFrameworkCore;
using Rbac.Domain;
using Rbac.Domain.Admins;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Rbac.Repository.Admins
{
    /// <summary>
    /// 抽象
    /// </summary>
    public class AdminRepository : BaseRepository<Admin>, IAdminRepository
    {
        /// <summary>
        /// 依赖注入db上下文向基类的BaseRepository的db传值
        /// </summary>
        /// <param name="admindb"></param>
        public AdminRepository(RbacDbContext admindb)
        {
            this.db = admindb;
        }

        public Admin QueryByName(string UserName)
        {
            return db.Admins.FirstOrDefault(m => m.UserName == UserName);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="Id"></param>
        public int ManyDelete(List<int> Id)
        {
            var list = db.Admins.Where(x => Id.Contains(x.AdminId)).ToList();
            list.ForEach(m => {
                //判断是否上传文件并删除旧文件
                if (File.Exists($"{Directory.GetCurrentDirectory()}/wwwroot{m.HeaderImage}"))
                    File.Delete($"{Directory.GetCurrentDirectory()}/wwwroot{m.HeaderImage}");
            });
            db.Admins.RemoveRange(list);
            return db.SaveChanges();
        }
    }
}
